#include "MultiplayerGame.h"

MultiplayerGame::MultiplayerGame(void)
{
}

MultiplayerGame::~MultiplayerGame(void)
{
}

int main(int argc, char *argv[])
{
	try
	{
		bool quit = false;
        while (!quit)
        {
			StartWindow startWindow;
            startWindow.excecute();
            switch (startWindow.getOptionSelected())
			{
				case(1):
					{
						MultiplayerGameServer* server = new MultiplayerGameServer(startWindow.getSceneSelected(), startWindow.getPort());
						GamePlayerClient* client = new GamePlayerClient(startWindow.getUserName(), startWindow.getPort());

						ClientSender* sender = new ClientSender(client);
						ClientReceiver* receiver = new ClientReceiver(client);
						
						Thread* serverThread = ThreadPool::getInstance()->execute(server);
						client->connectToServer();
						
						client->beginSession();
						if (client->isInitialized())
						{
							Thread* senderThread = ThreadPool::getInstance()->execute(sender);
							Thread* receiverThread = ThreadPool::getInstance()->execute(receiver);
							PlaygroundWindow playgroundWindow(client);
							playgroundWindow.excecute();
							
							senderThread->stop();
							receiverThread->stop();
							serverThread->stop();
							client->disconnectFromServer();

							delete sender;
							delete receiver;
							delete server;
						}
						delete client;
					}
					break;
				case(2):
					{	
						GamePlayerClient* client = new GamePlayerClient(startWindow.getUserName(), startWindow.getIP(), startWindow.getPort());
						client->connectToServer();
						if (client->isConnected())
						{
							client->beginSession();
							if (client->isInitialized())
							{
								cout << "The player background is " << client->getBackgroundFile() << "." << endl;
								ClientSender* sender = new ClientSender(client);
								ClientReceiver* receiver = new ClientReceiver(client);
						
								Thread* senderThread = ThreadPool::getInstance()->execute(sender);
								Thread* receiverThread = ThreadPool::getInstance()->execute(receiver);
								PlaygroundWindow playgroundWindow(client);
								playgroundWindow.excecute();
							
								client->endSession();

								senderThread->stop();
								receiverThread->stop();
								client->disconnectFromServer();

								delete sender;
								delete receiver;
							}
							delete client;
						}
						else
						{
							cout << "Unable to connect to server." << endl;
						}
					}
					break;
				default:
					quit=true;
			}
        }
    }
	catch (SDL_Exception &ex)
    {
        cout << ex.getMessage() << endl;
    }
	
	system("PAUSE");
	return 0;
}
